﻿using System;
using System.Collections.Generic;
using System.Linq;
using Aierp.Entities;
using Aierp.Repository;
using Aierp.SystemEntities.System;
using Aierp.Utility;
using Aierp.Utility.Core;
using Aierp.Utility.Data;
using Chloe;

namespace Aierp.SystemRepository.Implements
{
    public class UserRepository : DbInstance, IUserRepository
    {
        public const string OriginalPass = "123a";

        public int Login(string userName, string passWord, SysVisitor sysVisitor)
        {
            IQuery<Sys_Users> users = Db.Query<Sys_Users>();
            var user = users.Where(a => a.UserName == userName).FirstOrDefault();

            if (user == null) return 0;

            //账户禁用
            if (user.IsDisabled)
            {
                return -2;
            }
            //验证密码是否正确
            //string md5Pass = StringHelper.MD5string(passWord + user.PassSalt);
            var md5Pass = Md5.md5(passWord + user.PassSalt, 32);
            if (user.Password.Equals(md5Pass, StringComparison.OrdinalIgnoreCase))
            {
                sysVisitor.UserId = user.KeyId;
                sysVisitor.UserName = user.UserName;
                sysVisitor.IsAdmin = user.IsAdmin;

                sysVisitor.CurrentUser = user;

                return 1;
            }
            else
            {
                return 0;
            }
        }

        public int Add(Sys_Users item)
        {
            if (item == null) return 0;

            var result = this.Find(item.UserName);
            if (result != null) return -2;

            item.AddTime = DateTime.Now;
            item.PassSalt = Md5.randomString();
            item.Password = Md5.md5(Md5.md5(OriginalPass, 32) + item.PassSalt, 32);
            var ret = Db.Insert(item);

            return ret?.KeyId ?? 0;
        }

        /// <summary>
        /// 查询一个用户-根据用户名
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Sys_Users Find(string key)
        {
            IQuery<Sys_Users> users = Db.Query<Sys_Users>();
            var result  =users.Where(c => c.UserName == key).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 查询一个用户-根据ID，只返回指定信息，密码等关键信息不返回
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object FindById(int key)
        {
            IQuery<Sys_Users> users = Db.Query<Sys_Users>();
            var result = users.Where(c => c.KeyId == key).Select(a => new { a.KeyId, a.UserName, a.TrueName, a.DepartmentId, a.Mobile, a.QQ, a.Remark, a.IsAdmin, a.IsDisabled }).FirstOrDefault();
            return result;
        }

        public IEnumerable<Sys_Roles> GetRolesBy(int userId)
        {
            return null;
        }

        /// <summary>
        /// 获取一个列表，供给Grid使用
        /// </summary>
        /// <param name="sortOrder"></param>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="searchTxt"></param>
        /// <returns></returns>
        public string GetList(string sortOrder, int limit, int offset,string searchTxt)
        {
            IQuery<Sys_Users> users= Db.Query<Sys_Users>(); ;

            var total = users.Count();
            if (limit > 1000) limit = 100;
            if (limit > total)
            {
                limit = total;
                offset = 0;
            }
            else
            {
                if (offset >= total - limit) offset = total - limit;
            }
            users = (string.IsNullOrEmpty(sortOrder) || sortOrder == "asc") ? users.OrderBy(a => a.KeyId) : users.OrderByDesc(a => a.KeyId);
            if (!string.IsNullOrEmpty(searchTxt))
            {
                users = users.Where(c => c.UserName.Contains(searchTxt) || c.TrueName.Contains(searchTxt));
            }
            var ret = users.Select(a => new { a.KeyId, a.UserName, a.TrueName, a.DepartmentId, a.Mobile, a.Remark, a.IsAdmin, a.IsDisabled }).Skip(offset).Take(limit).ToList();

            return JSONhelper.GetJsonforBootstrapTable(total, ret);
        }

        /// <summary>
        /// 用户停用
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int Remove(int key)
        {
            IQuery<Sys_Users> users = Db.Query<Sys_Users>();
            var result = users.Where(c => c.KeyId == key).FirstOrDefault();

            //要判断是否admin管理员，用户名为admin的管理员不能删除
            if (result.UserName == "admin") return -9;

            //删除用户表
            var ret =  Db.DeleteByKey<Sys_Users>(key);
            //删除用户角色表
            Db.DeleteByKey<Sys_UserRoles>(key);
            return ret;
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public int Update(Sys_Users item)
        {
            //先检查用户是否存在
            var user = this.Find(item.UserName);
            if (user == null) return -2;
            //更新
            Db.TrackEntity(user);//在上下文中跟踪实体
            user.TrueName = item.TrueName;
            user.Mobile = item.Mobile;
            user.QQ = item.QQ;
            user.IsAdmin = item.IsAdmin;
            user.IsDisabled = item.IsDisabled;
            user.Remark = item.Remark;

            return Db.Update(user);//这时只会更新被修改的字段

        }

        /// <summary>
        /// 更新用户-更新我的信息-只更新3个字段
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public int UpdateMyInfo(Sys_Users item)
        {
            //先检查用户是否存在
            var user = this.Find(item.UserName);
            if (user == null) return -2;
            //更新
            Db.TrackEntity(user);//在上下文中跟踪实体
            user.TrueName = item.TrueName;
            user.Mobile = item.Mobile;
            user.QQ = item.QQ;

            return Db.Update(user);//这时只会更新被修改的字段

        }

        /// <summary>
        /// 返回当前用户是否管理员-添加更新删除用户操作，只有超级管理员才可以进行，以上三步操作，需要判断用户是否是超级管理员工
        /// </summary>
        /// <param name="sysVisitor"></param>
        /// <returns></returns>
        public bool CheckUser(SysVisitor sysVisitor)
        {
            return sysVisitor.IsAdmin;
        }

        public int ChangePassWord(int userId, string oldPass, string newPass)
        {
            IQuery<Sys_Users> users = Db.Query<Sys_Users>();
            var u = users.Where(c => c.KeyId == userId).FirstOrDefault();
            if (u == null) return -2;
            oldPass = Md5.md5(oldPass + u.PassSalt, 32);
            if (oldPass != u.Password) return -9;

            Db.TrackEntity(u);//在上下文中跟踪实体
            u.Password = Md5.md5(newPass + u.PassSalt, 32);//更改密码//更改密码
            return Db.Update(u);
        }

        public int ResetPassWord(int userId)
        {
            IQuery<Sys_Users> users = Db.Query<Sys_Users>();
            var u = users.Where(c => c.KeyId == userId).FirstOrDefault();
            if (u == null) return -2;
            Db.TrackEntity(u);//在上下文中跟踪实体

            u.Password = Md5.md5(Md5.md5(OriginalPass,32) + u.PassSalt, 32);//更改密码

            return Db.Update(u);
        }

        public int GetHtmlVersion()
        {
            IEnumerable<int> version = Db.SqlQuery<int>("select ConfigValue from Sys_Config where ConfigName='HtmlVersion'");
            var enumerable = version as int[] ?? version.ToArray();
            return enumerable[0];
        }
    }
}
